package com.xzx.framework.util.sendsms;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.xzx.framework.enumUtil.AliSmsCode;
import com.xzx.framework.util.PropertiesUtil;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;
/**
 * 阿里云短信服务调用方法（已完成）
* @ClassName: AliSendSMS    
* @Description:     
* @author xzx   
* @date 2018年3月6日 下午6:08:07    
*
 */
public class AliSendSMS {
	
	private static Logger log = Logger.getLogger(AliSendSMS.class);
	
    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    static final PropertiesUtil util = new PropertiesUtil("alisendsms.properties");
    static final String accessKeyId = util.getProperty("accessKeyId");
    static final String accessKeySecret = util.getProperty("accessKeySecret");
    
    /**
     * 单个短信发送功能
     * @param templateCode 短信模板code
     * @param phones 接受短信手机号
     * @param signName 短信签名
     * @param templateParam 模板中的变量替换JSON串 例：{\"authcode\":\"252525\"}
     * @return
     */
    public static boolean sendSms(String templateCode,String phone,String signName,String templateParam){
    	try {
	        //可自助调整超时时间
	        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
	        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
	        //初始化acsClient,暂不支持region化
	        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
	        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
	        IAcsClient acsClient = new DefaultAcsClient(profile);
	        //组装请求对象-具体描述见控制台-文档部分内容
	        SendSmsRequest request = new SendSmsRequest();
	        //必填:待发送手机号
	        request.setPhoneNumbers(phone);
	        //必填:短信签名-可在短信控制台中找到
	        request.setSignName(signName);
	        //必填:短信模板-可在短信控制台中找到
	        request.setTemplateCode(templateCode);
	        //可选:模板中的变量替换JSON串
	        if(null!=templateParam &&!"".equals(templateParam)){
	        	request.setTemplateParam(templateParam);
	        }
	        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
	        //request.setSmsUpExtendCode("90997");
	        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
	       // request.setOutId("yourOutId");
	        //hint 此处可能会抛出异常，注意catch
	        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
	        if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
	        	log.info("Code=" + sendSmsResponse.getCode());
	        	log.info("Message=" + sendSmsResponse.getMessage());
	        	log.info("RequestId=" + sendSmsResponse.getRequestId());
	        	return true;
	        }else if(sendSmsResponse.getCode() != null&&!sendSmsResponse.getCode().equals("OK")) {
	         	log.info("Code=" + sendSmsResponse.getCode());
	        	log.info("Message=" + sendSmsResponse.getMessage());
	        	log.info("RequestId=" + sendSmsResponse.getRequestId());
	        	log.info(AliSmsCode.fromTypeName(sendSmsResponse.getCode()));
	        }else{
	        	log.error("·········阿里单个短信发送接口返回结果为空············");
	        }
		} catch (Exception e) {
			log.error("···········阿里单个短信发送接口调用异常···········");
			e.printStackTrace();
		}
    	return false;
    }
    /**
     * 批量短信发送功能
     * @param templateCode 短信模板code
     * @param phones 手机号数组  例：{"13146540623","13994186929"}
     * @param signName 短信签名数组  例：{"镜观","镜观"}
     * @param templateParam  模板中的变量替换JSON串  例：[{\"authcode\":\"252525\"},{\"authcode\":\"252525\"}]
     * @return
     */
    public static boolean sendSmsEs(String templateCode,String[] phones,String[] signName,String templateParam){
    	try {
	        //可自助调整超时时间
	        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
	        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
	        //初始化acsClient,暂不支持region化
	        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
	        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
	        IAcsClient acsClient = new DefaultAcsClient(profile);
	        //组装请求对象-具体描述见控制台-文档部分内容
	        SendBatchSmsRequest request = new SendBatchSmsRequest();
	        //必填:待发送手机号
	        request.setPhoneNumberJson(JSON.toJSONString(phones));
	        //必填:短信签名-可在短信控制台中找到
	        request.setSignNameJson(JSON.toJSONString(signName));
	        //必填:短信模板-可在短信控制台中找到
	        request.setTemplateCode(templateCode);
	        //可选:模板中的变量替换JSON串
	        if(null!=templateParam &&!"".equals(templateParam)){
	        	request.setTemplateParamJson(templateParam);
	        }
	        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
	        //request.setSmsUpExtendCode("90997");
	        //hint 此处可能会抛出异常，注意catch
	        SendBatchSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
	        if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
	        	log.info("Code=" + sendSmsResponse.getCode());
	        	log.info("Message=" + sendSmsResponse.getMessage());
	        	log.info("RequestId=" + sendSmsResponse.getRequestId());
	        	return true;
	        }else if(sendSmsResponse.getCode() != null&&!sendSmsResponse.getCode().equals("OK")) {
	         	log.info("Code=" + sendSmsResponse.getCode());
	        	log.info("Message=" + sendSmsResponse.getMessage());
	        	log.info("RequestId=" + sendSmsResponse.getRequestId());
	        	log.info(AliSmsCode.fromTypeName(sendSmsResponse.getCode()));
	        }else{
	        	log.error("·········阿里单个短信发送接口返回结果为空············");
	        }
		} catch (Exception e) {
			log.error("···········阿里批量短信发送接口调用异常···········");
			e.printStackTrace();
		}
    	return false;
    }

    /**
     * 短信明细查询接口
     * @param phone（必填） 查询发送手机号
     * @param bizId 流水号
     * @param dateTime（必填） 发送时间
     * @param page（必填） 第几页
     * @param pageSize（必填） 每页多少条数据
     * @return
     * @throws ClientException
     */
    public static QuerySendDetailsResponse querySendDetails(String phone,String bizId,Date dateTime,Long page,Long pageSize){
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        try {
	        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
	        IAcsClient acsClient = new DefaultAcsClient(profile);
	        //组装请求对象
	        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
	        //必填-号码
	        request.setPhoneNumber(phone);
	        //可选-流水号
	        if(null!=bizId&&""!=bizId){
	        	request.setBizId(bizId);
	        }
	        //必填-发送日期 支持30天内记录查询，格式yyyyMMdd
	        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
	        request.setSendDate(ft.format(dateTime));
	        //必填-页大小
	        request.setPageSize(pageSize);
	        //必填-当前页码从1开始计数
	        request.setCurrentPage(page);
	        //hint 此处可能会抛出异常，注意catch
	        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);
	        return querySendDetailsResponse;
		}catch (Exception e) {
			log.error("···········阿里短信明细查询接口查询异常···········");
			e.printStackTrace();
		}
        return null;
    }

    public static void main(String[] args) throws ClientException, InterruptedException {
        // 单个短信发送
    	//boolean response = sendSms("SMS_123290297", "13146540623", "镜观", "{\"authcode\":\"252525\"}");
    	//System.out.println(response);
    	
    	//多个短信发送
//    	System.out.println("···············短信接口返回的数据----------------");
//    	String [] phone = {"13146540623","13994186929"};
//    	String [] name = {"镜观","镜观"};
//    	boolean re = sendSmsEs("SMS_123290297",phone,name, "[{\"authcode\":\"252525\"},{\"authcode\":\"252525\"}]");
//        System.out.println(re);
    	
    	//结果查询
    	
        QuerySendDetailsResponse querySendDetailsResponse = querySendDetails("13146540623", null, new Date(), 1L, 10L);
        System.out.println("短信明细查询接口返回数据----------------");
        System.out.println("Code=" + querySendDetailsResponse.getCode());
        System.out.println("Message=" + querySendDetailsResponse.getMessage());
        Integer i = 0;
        for(QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs())
        {
            System.out.println("SmsSendDetailDTO["+i+"]:");
            System.out.println("Content=" + smsSendDetailDTO.getContent());
            System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
            System.out.println("OutId=" + smsSendDetailDTO.getOutId());
            System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
            System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
            System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
            System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
            System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
        }
        System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
        System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
        
        		System.out.println((i instanceof Integer));
    }
}
